package com.xlf.common.controller;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import com.xlf.cache.CatalogList;
import com.xlf.cache.Option;
import com.xlf.cache.OrderStatusList;
import com.xlf.cache.PlanPrice;
import com.xlf.common.interceptor.DesignerInterceptor;
import com.xlf.common.model.Order;
import com.xlf.common.model.OrderCatalog;
import com.xlf.common.model.OrderItem;
import com.xlf.common.model.Product;
import com.xlf.common.model.User;
import com.xlf.util.ModelCopier;
import com.xlf.web.SessionCar;
import com.xlf.web.SessionCatalog;
import com.xlf.web.SessionItem;
import com.xlf.web.SessionKey;

@Before(DesignerInterceptor.class)
public class DesignerController extends Controller {

	@ClearInterceptor
	public void test() {
		renderJsp("order_res.jsp");
	}

	@ClearInterceptor
	public void login() {
		renderJsp("login.jsp");
	}

	public void plan() {
		renderJsp("plan.jsp");
	}

	public void viewOrder() {
		String oid = getPara("oid");
		Order order = Order.dao.findById(oid);
		List<OrderCatalog> orderCatalogs = order.getOrderCatalogs();

		setAttr("order", order);
		setAttr("orderCatalogs", orderCatalogs);

		renderJsp("view_order.jsp");
	}

	/**
	 * 删除订单 订单状态要求为 0-未审核
	 */
	public void deleteOrder() {
		String oid = getPara("oid");
		Order order = Order.dao.findById(oid);
		if (order != null && order.getInt("status") == 0) {
			Order.dao.deleteOrderInfo(oid);
		}

		setAttr("deleteNotice", "撤销成功");

		listOrder();
	}

	/**
	 * 浏览订单 设计师(user.type=21)仅可以浏览属于自己的订单
	 * 设计经理(user.type=20)/主材部(user.type=10/11)可以浏览全部订单
	 */
	public void listOrder() {
		// 获取当前管理员信息
		User designer = getSessionAttr(SessionKey.USER);
		int userType = designer.getInt("type");
		String uid = null;
		if (userType == 21) {
			// 仅可浏览自己的订单
			uid = Integer.toString(designer.getInt("u_id"));
		} else {
			// 可浏览全部订单
		}

		List<Option> orderStatusList = OrderStatusList.getList();
		setAttr("orderStatusList", orderStatusList);

		// 检索条件
		int status = getParaToInt("status", -1);
		setAttr("status", status);
		String oid = getPara("oid", null);
		String deleteNotice = getAttrForStr("deleteNotice");
		if (deleteNotice != null) {
			// 通过删除操作过来的业务
			oid = null;
			setAttr("deleteNotice", deleteNotice);
		}
		setAttr("oid", oid);

		Page<Order> pageRecord = Order.dao.exeSearchSql(getParaToInt("page", 1), 20, oid, uid, null, null, status);
		setAttr("pageRecord", pageRecord);

		renderJsp("list_order.jsp");
	}

	public void chooseProduct() {
		String init = getPara("init");
		if (init != null && init.equals("true")) {
			// 第一次选择商品，清空Session缓存信息
			removeSessionAttr(SessionKey.CAR);
			removeSessionAttr(SessionKey.PLAN_TYPE_STR);

			setSessionAttr(SessionKey.CAR, new SessionCar());
			// session中保存套餐类型
			String planType = getPara("planType");
			setSessionAttr(SessionKey.PLAN_TYPE_STR, planType);
		}

		// 查询条件
		String catalogId = getPara("catalogId");
		if (catalogId == null) {
			catalogId = "1";
		}
		String type = getPara("type");

		// 设置查询条件，用于页面回显
		setAttr("catalogId", catalogId);
		setAttr("type", type);

		List<Option> catalogList = CatalogList.getList();
		setAttr("catalogList", catalogList);

		// 查询商品列表
		Page<Product> pageRecord = Product.dao.exeSearchSql(
				getParaToInt("page", 1), 20, catalogId, type, null, null,
				(String) getSessionAttr(SessionKey.PLAN_TYPE_STR), null);
		setAttr("pageRecord", pageRecord);

		renderJsp("choose_product.jsp");
	}

	public void createOrder() {
		SessionCar sessionCar = getSessionAttr(SessionKey.CAR);
		setAttr("sessionCar", sessionCar);

		// 创建订单ID
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmSS");
		String orderId = sdf.format(new Date());
		setAttr("orderId", orderId);

		sdf = new SimpleDateFormat("yyyy-MM-dd");
		setAttr("createTime", sdf.format(new Date()));

		// 公司信息
		User designer = getSessionAttr(SessionKey.USER);
		setAttr("designer", designer);

		// 购物车信息
		SessionCar car = getSessionAttr(SessionKey.CAR);
		setAttr("sessionCar", car);

		// 订单信息
		String planType = getSessionAttr(SessionKey.PLAN_TYPE_STR);
		setAttr("planType", planType);

		if (planType.equals("4")) {
			// 自选套餐，需要动态计算价格
			double totalPrice = getTotalPrice();
			setAttr("price", totalPrice);
		} else {
			// 获取套餐标准定价
			setAttr("price", PlanPrice.getPrice(planType));
		}

		renderJsp("order.jsp");
	}

	/**
	 * 计算购物车内商品总价（自选套餐）
	 * 
	 * @return
	 */
	private double getTotalPrice() {
		double totalPrice = 0;
		SessionCar car = getSessionAttr(SessionKey.CAR);
		List<SessionCatalog> sessionCatalogs = car.getSessionCatalogs();
		for (SessionCatalog sessionCatalog : sessionCatalogs) {
			Map<Integer, SessionItem> sessionItemsMap = sessionCatalog
					.getSessionItems();
			if (sessionItemsMap != null && sessionItemsMap.size() > 0) {
				Collection<SessionItem> sessionItems = sessionItemsMap.values();
				for (SessionItem sessionItem : sessionItems) {
					totalPrice += sessionItem.getPrice()
							* sessionItem.getCount();
				}
			}
		}
		
		// 保留小数后2位
		return keepDigits2(totalPrice);
	}

	public void saveOrder() {
		String notice = "";
		try {
			// 处理上传文件-房屋合同照片
			UploadFile contractImg = getFile("contractImg", "contract");
			// System.out.println(contractImg.getSaveDirectory());

			// 从页面获取Order基本信息
			Order order = getModel(Order.class);
			order.set("createTime", new Date());
			// 设置合同图片路径
			if (contractImg != null) {
				order.set("contractPic", contractImg.getFileName());
			}
			// 新生成订单默认状态为0，未审核
			order.set("status", 0);
			order.save();

			// 遍历SessionCar取当前订单详细信息
			SessionCar sessionCar = getSessionAttr(SessionKey.CAR);
			List<SessionCatalog> sessionCatalogs = sessionCar
					.getSessionCatalogs();
			for (SessionCatalog sessionCatalog : sessionCatalogs) {
				if (sessionCatalog.getSessionItems().size() > 0) {
					OrderCatalog orderCatalog = new OrderCatalog();
					orderCatalog.set("o_id", order.get("o_id"));
					// 获取订单页面填写的CatalogRemark
					orderCatalog.set("catalogRemark", getPara("catalogRemark" + sessionCatalog.getC_id()));
					ModelCopier.copyBeanToModel(sessionCatalog, orderCatalog);
					orderCatalog.save();

					// 获取订单明细
					Map<Integer, SessionItem> sessionItems = sessionCatalog.getSessionItems();
					Set<Integer> keys = sessionItems.keySet();
					for (Integer key : keys) {
						OrderItem orderItem = new OrderItem();
						orderItem.set("o_id", order.get("o_id"));
						orderItem.set("oc_id", orderCatalog.get("oc_id"));

						SessionItem sessionItem = sessionItems.get(key);
						ModelCopier.copyBeanToModel(sessionItem, orderItem);
						
						if(sessionCatalog.getC_id() == 9) {
							// 小件商品自动补充送货时间 量尺时间
							orderItem.set("scaleTime", new Date());
							orderItem.set("deliverTime", new Date());
						}
						
						orderItem.save();
					}
				}
			}
			notice = "<font color='blue'>订单保存成功</font>";
		
		} catch (Exception ex) {
			ex.printStackTrace();
			notice = "<font color='red'>系统错误:" + ex.getMessage() + "</font>";
		}

		setAttr("notice", notice);

		renderJsp("order_res.jsp");
	}

	public void addToCar() {
		int pid = getParaToInt("pid");
		Product product = Product.dao.findById(pid);
		setAttr("catalogName", CatalogList.getName(product.getInt("c_id")));
		setAttr("product", product);

		renderJsp("add_to_car.jsp");
	}
	
	/**
	 * 保留小数后2位
	 * @param number
	 * @return
	 */
	private double keepDigits2(double number) {
		BigDecimal b = new BigDecimal(number);
		return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	public void saveItem() {
		int pid = getParaToInt("pid");
		int cid = getParaToInt("cid");
		
		double count = 0;
		if(cid == 3) {
			// 橱柜 分上下尺寸
			String topCountStr = getPara("topCount");
			String bottomCountStr = getPara("bottomCount");
			
			double result = (Double.parseDouble(topCountStr) * 0.3) + (Double.parseDouble(bottomCountStr) * 0.7);
			count = keepDigits2(result);
		} else {
			// 其他
			String countStr = getPara("count");
			count = Double.parseDouble(countStr);
		}
		
		String location = getPara("location");
		String remark = getPara("remark");

		// 组织Item保存至Session
		Product product = Product.dao.findById(pid);
		SessionItem item = new SessionItem();

		ModelCopier.copyModelToBean(product, item);
		item.setCount(count);
		item.setLocation(location);
		item.setItemRemark(remark);

		SessionCar sessionCar = getSessionAttr(SessionKey.CAR);
		sessionCar.addItem(item);

		setAttr("closeWindow", "true");
		renderJsp("add_to_car.jsp");
	}

	public void showCar() {
		SessionCar sessionCar = getSessionAttr(SessionKey.CAR);
		setAttr("sessionCar", sessionCar);

		renderJsp("show_car.jsp");
	}

	public void deleteItem() {
		int cid = getParaToInt("cid");
		int pid = getParaToInt("pid");

		SessionCar sessionCar = getSessionAttr(SessionKey.CAR);
		sessionCar.removeItem(cid, pid);

		showCar();
	}

}
